package com.zluyuer.ermu;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.zluyuer.ermu.msg.Message;

public class ErmuClient {

    private static Logger log = Logger.getLogger(ErmuClient.class);

    private Socket socket;
    private PrintWriter writer;
    private int sendBufferSize = 4096;
    
    
    public void connect(String ip, int port) throws IOException {
        try {
            close();
        } catch (IOException e) {}
        
        log.info("Connecting to " + ip + ":" + port);
        
        socket = new Socket();
        socket.setTcpNoDelay(true);
        socket.connect(new InetSocketAddress(ip, port));
        socket.setSendBufferSize(sendBufferSize);
        writer = ErmuHelper.getSocketPrintWriter(socket);
        
        log.info("Connected to " + ip + ":" + port + " successfully");
    }
    
    public void close() throws IOException {
        if (socket != null && socket.isConnected()) {
            log.info("Closing ErmuClient...");
            
            socket.close();
            socket = null;
            
            log.info("ErmuClient closed successfully");
        }
    }
    
    public void send(Message msg) throws Exception {
        writer.write(msg.toXML());
        writer.write('\0');
        writer.flush();
        
        log.debug("Sent msg: " + msg.getCode() + "-" + msg.getId());
    }
    
    public void setSendBufferSize(int sendBufferSize) {
        this.sendBufferSize = sendBufferSize;
    }
}
